package ysother

import (
	"gitee.com/kmyss/gf-ex/yslog"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/os/gtime"
)

func BackFile(path string) error {
	baseName := gfile.Basename(path)
	dir := gfile.Dir(path)
	srcPath := gfile.Abs(path)
	bakPath := gfile.Abs(dir + "/bak/" + baseName + gtime.Now().Format("YmdHis") + ".bak")
	
	if gfile.Exists(srcPath) {
		bakDir := gfile.Dir(bakPath)
		if !gfile.Exists(bakDir) {
			if err := gfile.Mkdir(bakDir); err != nil {
				return err
			}
		}
		err := gfile.Copy(srcPath, bakPath)
		if err != nil {
			return err
		}
		yslog.Printf("* 备份 %s 到 %s", gfile.Basename(srcPath), "./bak/"+gfile.Basename(bakPath))
	}
	return nil
}
